#服务的实现
from shared_memory_dict import SharedMemoryDict
import dao, utils

def user_login(name: str, pwd: str)->str:
    user_id = dao.get_user_id(name, pwd)
    if user_id==None:
        raise Exception("Invalid user name or password.")
    session:dao.Session = dao.create_session(user_id, dao.Session.OT_USER)
    if session:
        return session.token
    raise Exception("Create user session failed.")

def device_verify(key: str)->str:
    device_id = dao.get_device_id(key)
    if device_id == None:
        raise Exception("Invalid device key.")
    session:dao.Session = dao.create_session(device_id, dao.Session.OT_DEVICE)
    if session:
        return session.token
    raise Exception("Create device session failed.")

def verify_device_token(token: str)->bool:
    session = dao.get_session(token, dao.Session.OT_DEVICE)
    if session:
        return True
    else:
        return False

def verify_user_token(token: str)->bool:
    session = dao.get_session(token, dao.Session.OT_USER)
    if session:
        return True
    else:
        return False

def device_beat(data: dict)->dict:
    #将数据写入数据库
    dd = dao.DeviceData()
    dd.from_json(data)
    dd.time = utils.now_str()
    _id = dao.insert_device_data(dd)
    #获取led灯状态
    state:dao.LEDState = dao.get_last_led_state()
    if state:
        return {"led_state": state.state}
    else:
        return {"led_state": False}

def set_led_state(state: bool):
    ls = dao.LEDState()
    ls.state = state
    ls.time = utils.now_str()
    dao.insert_led_state(ls)

def get_led_state():
    ls = dao.get_last_led_state()
    if ls:
        return ls.state
    else:
        return False

def get_device_data(from_time, to_time):
    ret=[]
    dds = dao.get_device_data(from_time, to_time)
    if dds:
        for dd in dds:
            ret.append(dd.to_json())
    return ret

if __name__ == "__main__":
    #print(device_beat({'temperature':12, 'pressure':23.2323, 'votage':1.2332, 'position':10,'switch':True}))
    #print(get_device_data(None, None))
    #print(verify_user_token('66797e316972a06d9eccaaa4'))
    print(device_beat({
    "temperature": 76,
    "pressure": 99,
    "voltage": 14,
    "position": 44,
    "switch": False
}))